package org.edu.common.listener;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.apache.log4j.Logger;
import org.edu.common.uiltst.UserStatic;
import org.edu.model.User;

public class SessionListener implements ServletContextListener,
		HttpSessionListener, HttpSessionAttributeListener {

	private ServletContext application = null;
	private static final Logger logger = Logger
			.getLogger(SessionListener.class);
	private UserStatic usta = UserStatic.getInit();

	// 这个方法在Web应用服务被移除，没有能力再接受请求的时候被调用。
	public void contextDestroyed(ServletContextEvent arg0) {
		// TODO Auto-generated method stub
		System.out.println("过期");

	}

	// 这个方法在Web应用服务做好接受请求的时候被调用。
	public void contextInitialized(ServletContextEvent arg0) {
		this.application = arg0.getServletContext();
		this.application.setAttribute("allusers", new ArrayList<User>());
		logger.info("开始");
	}

	public void attributeAdded(HttpSessionBindingEvent arg0) {
		@SuppressWarnings("unchecked")
		List<User> l = (List<User>) this.application.getAttribute("allusers");
		if (arg0.getValue() instanceof User) {
			logger.info("监听器：" + ((User) arg0.getValue()).getAccount() + "登录");
			l.add((User) arg0.getValue());
			this.application.setAttribute("allusers", l);
		}
		// System.out.println("userDao.ger():"+userDao.get("admin"));
	}

	public void attributeRemoved(HttpSessionBindingEvent arg0) {
		// TODO Auto-generated method stub

	}

	public void attributeReplaced(HttpSessionBindingEvent arg0) {
		// TODO Auto-generated method stub

	}

	public void sessionCreated(HttpSessionEvent arg0) {
		// TODO Auto-generated method stub

	}

	public void sessionDestroyed(HttpSessionEvent arg0) {
		@SuppressWarnings("unchecked")
		List<User> l = (List<User>) this.application.getAttribute("allusers");

		User value = (User) arg0.getSession().getAttribute("user");
		if (null != value) {
			// logger.info("监听器：" + value.getAccount() + "用户离线");
			l.remove(value);
			value.setOffline(new Date());
			usta.getL().add(value);
			this.application.setAttribute("allusers", l);
		}

	}

}
